const Actions = require('./actions');
const DB = require('app/db.js');
import { guid,getTime,getMarkdownText,sendNotice} from 'clientConfig/util/queryurlfield';
const monStorage = require('clientConfig/util/StoreData').monStorage;
const Storage = require('clientConfig/util/StoreData').Storage;
const { Toast } = SaltUI;
import { Control } from 'react-keeper';

let form_component_values = null;
// let upfileName = []
// let upimageName = []

module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {
    },

    onFetch: function (params, cb) {
        let t = this;
        // upfileName = []
        // upimageName = []
        DB.Approval.get_approval_list({
                module_type: "workplan",
                proj_category: 'software',
                status:'8',
                PageNum: 0,
                CountForAPage: 100,
                id: Storage.get('user.id')
            })
            .then((content) => { // 成功
                var proNumAll = [];
                var proNameAll = [];
                var folderId = [];
                var webhookAll = [];
                if(content.list instanceof Array){
                    content.list.map((item, index)=>{ 
                        var obj = {}
                        obj.value = index;
                        obj.text = item.proj_name; 
                        proNameAll.push(obj);
                        proNumAll.push(item.proj_num);
                        folderId.push(item.folder_id)
                        webhookAll.push(item.proj_webhook);
                    })
                }
                t.data.proNumAll = proNumAll
                t.data.proNameAll = proNameAll
                t.data.folderId = folderId;
                t.data.webhookAll = webhookAll
                // t.data.upfileName = []
                // t.data.upimageName = []
                t.updateComponent();
            })
            .catch((error) => { // 失败 or 有异常被捕获

            });
    },
    onSendForm: function (params,contents,boo) {
        let t = this;
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();        
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = Storage.get('user.id') //审批发起人的userid
        let dept_id = monStorage.get('user.department');
        let approvers = contents.spr;
        let approvers_id = contents.approvers_id;
        let cc_list = contents.csr;
        let cc_list_id = contents.cc_list_id;
        let folder_id = params.data.folder_id;
        var array = [];
        if(approvers instanceof Array){
            for (let i = 0; i < approvers.length; i++) {
                array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
            }
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ content: "", file: "", imgae: "" });
        let next_cursor = 0;
        const status = 1;
        const module_type = "maintenance";
        const proj_category = !boo ? "faultreq" : "changereq";
        const proj_num = params.data.proNum;
        const proj_name = params.data.proName.text;
        const proj_webhook = contents.proj_webhook;
        const proj_markdown = getMarkdownText({create_time, originator_user,approvers, proj_name, proj_num, status,title:"故障上报"})
        const process_id = guid();
        var nodelists = [];
        let node_info = [];
        if(!boo){
            node_info.push({name: "维护负责人",value: approvers instanceof Array ? approvers[0] : ''},{name: "维护验收人",value: approvers instanceof Array ? approvers[1] : ''});
        }
        for(let i=0; i<params.node.length;i++){
            var obj = {}
            if(params.node[i].name=="上传附件" || params.node[i].name=="上传图片"){
                obj.value = JSON.stringify(params.data[params.node[i].formOption]);
            }else{
                obj.value = params.data[params.node[i].formOption];
            }
            obj.name = params.node[i].name;
            node_info.push(obj);
        }
        var obj = {}
        obj.node_info = node_info
        Object.assign(obj,{node_name: !boo ? "faultreq" : "changereq",modified: !boo ? 0 : 1, permission:"1"})
        nodelists.push(obj);
        form_component_values = {
            content:{failure_number: process_id , proj_create_time: getTime()},
            nodelists: nodelists
        };
        var send = Object.assign({}, {agent_id, create_time, finish_time, originator_user, originator_user_id, dept_id, approvers, approvers_id, cc_list, cc_list_id, folder_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, proj_markdown, process_id, form_component_values})
        // console.log(send)
        if (params.pagedata) {
            send = this.modify(send, params);
            //console.log(send)
        }
        let notice_info = {
            "process_id": process_id,
            "no_read": true,
            "proj_num": proj_num,
            "proj_name": proj_name,
            "create_time": create_time,
            "status": status,
            "type":"待我审批的"
        }
        let noticed_lists = approvers_id instanceof  Array ? approvers_id[next_cursor] : approvers_id;
        DB.Approval.send_approval(send)
        .then((content) => { // 成功
            Toast.show({
                type: 'success',
                content: "提交成功",
            });
            sendNotice(noticed_lists, notice_info)
            Control.go(-1)
        })
        .catch((error) => { // 失败 or 有异常被捕获
            if(error.message){
                Toast.show({
                    type: 'error',
                    content: error.message
                });
            }else{
                Toast.show({
                    type: 'error',
                    content: '提交失败'
                });
            }
        });
    },
    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        let old_change = [];//变更前字段 发送群消息
        let new_change = [];//变更后字段 发送群消息
        let form_component_values_new = new_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        for (let i = 0; i < nodelists_new.length; i++) {
            let node_info_new = nodelists_new[i].node_info;
            let node_info_old = old_data.node_info;
            for (let j = 0; j < node_info_new.length; j++) {
                if(node_info_old[j].name == '维护负责人' || node_info_old[j].name == '维护验收人'){
                }else{
                    if(node_info_new[j-2].name == node_info_old[j].name){
                        if (node_info_new[j-2].value != node_info_old[j].value) {
                            node_info_new[j-2].ext_value = node_info_old[j].value//变更过
                            old_change.push(node_info_old[j].value);
                            new_change.push(node_info_new[j-2].value);
                        }
                    }
                }
            }
        }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, approvers_id, next_cursor, proj_name, proj_num, status } = { ...new_data };
        const proj_markdown = getMarkdownText({ old_change, new_change, change_type: edit ? "撤销申请" : "内容变更", create_time, originator_user, approvers: approvers[next_cursor], proj_name, proj_num, status,title: '维护支持' }, "change")
        new_data.proj_markdown = proj_markdown;
        return new_data;
    },

    updateComponent: function () {
        this.trigger(this.data);
    },

    getInitialState: function () {
        return this.data;
    }
});
